package com.test.servlet.login;

import com.test.pojo.User;
import com.test.service.UserServiceTmpl;
import com.test.util.Contents;
import org.junit.Test;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登陆处理
 * 控制层 调用 业务层
 */
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取参数
        String usercode = req.getParameter("usercode");
        String password = req.getParameter("password");
        // 调用业务层进行查询
        UserServiceTmpl userServiceTmpl = new UserServiceTmpl();
        // 获取登陆的人
        User user = userServiceTmpl.login(usercode, password);
        if(user != null ){
            //可以登陆
            //把用户数据放到session
            HttpSession session = req.getSession();
            session.setAttribute(Contents.USER_SESSION,user);
            //跳转到内部主页
            resp.sendRedirect("jsp/frame.jsp");
        }else{
            //登陆失败
            req.setAttribute("error","用户名或者密码不正确");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }
}
